// 引入工具类jwt
const {
    decode
} = require("jsonwebtoken");
let jwt = require("./jwt");
// 处理公共参数
module.exports = (req, res, next) => {
    // 地址栏数据
    // 因为从网页传递过来的是字符串,所以需要转成数字,这里-1是因为数据库从0开始
    // 还要有默认值,从配置文件中的global中引入
    req.query._page = req.query._page ? req.query._page - 1 : require("../config/global")._page;
    req.query._limit = req.query._limit ? req.query._limit - 0 : require('../config/global')._limit;
    req.query.q = req.query.q ? req.query.q : require('../config/global').q;
    req.query._sort = req.query._sort ? req.query._sort : require('../config/global')._sort;

    // 非地址栏数据
    req.body._page = req.body._page ? req.body._page - 1 : require('../config/global')._page;
    req.body._limit = req.body._limit ? req.body._limit - 0 : require('../config/global')._limit;
    req.body.q = req.body.q ? req.body.q : require('../config/global').q;
    req.body._sort = req.body._sort ? req.body._sort : require('../config/global')._sort;

    // 请求头
    req.headers._page = req.headers._page ? req.headers._page - 1 : require('../config/global')._page;
    req.headers._limit = req.headers._limit ? req.headers._limit - 0 : require('../config/global')._limit;
    req.headers.q = req.headers.q ? req.headers.q : require('../config/global').q;
    req.headers._sort = req.headers._sort ? req.headers._sort : require('../config/global')._sort;


    // 公共类授权
    // 登陆注册注销不需要授权
    if (/login|register|logout/.test(req.url)) {
        // 跳过
        next();
    } else {
        // token的来源
        let token = req.headers.token || req.body.token || req.query.token;
        // 校验token是否合法携带
        jwt.verify(token).then(
            decode => {
                console.log(decode);
                // 成功请求到token之后给请求的接口带过去
                req.query.decode = decode;
                next();
            }
        ).catch(
            message => {
                res.send({
                    err: 2,
                    msg: "token过期或无效" + message
                });
            }
        )
    }



}